// pages/home/home.js
import Service from '../../model/service'
import Category from '../../model/category'
import { throttle } from '../../utils/util';
import Tim from '../../model/tim';
const service = new Service();
Page({ 
  /**
   * 页面的初始数据
   */
  data: {
    tabs:['全部服务','在提供','正在找'],
    categoryList:[],
    currentTabIndex:0,
    serviceList:[],
    tabIndex:0,
    categoryId:0,
    loading:true
  }, 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) { 
    // new Tim()
    // Tim.getInstance()
   await this._getServiceList(); 
   // 获取分类列表
   await this._getCategoryList();

   this.setData({
    loading: false
   })
  },

  async _getServiceList(){
    const serviceList = await service.reset().getServiceList(this.data.categoryId,this.data.tabIndex);
    // console.log(serviceList);
    this.setData({
      serviceList 
    })
  },

  async _getCategoryList(){
    const  categoryList = await Category.getCategoryListWidthAll();
    // console.log(categoryList);
    this.setData({
      categoryList
    })
  },
  
  handleTabChnage(e){
    // console.log(e);
    let tabIndex = e.detail.index;
    console.log(tabIndex);
    this.data.tabIndex = tabIndex
    this._getServiceList()
  },

  handleCategoryChange: throttle(function(e){
    let categoryId = e.currentTarget.dataset.id;
    if(categoryId === this.data.categoryId) return;
    // console.log(categoryId);
    this.data.categoryId = categoryId
    this._getServiceList()
  }) ,
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },


  handleSelectService(e){ 
   let  service = e.currentTarget.dataset.service;
  //  console.log(service)
   wx.navigateTo({
     url: '/pages/service-detail/service-detail?service_id=' + service.id,
   })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh() {
    //  console.log('下拉刷新')
    this._getServiceList();
     // 主动隐藏 加载效果
     wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数 加载更多
   */
  async onReachBottom() {
    // 获取下一页的数据和当前的数据合并
    // console.log('上拉触底')  
    if(!service.hasMoreData){
      return ;
    }
    const serviceList = await service.getServiceList(this.data.categoryId,this.data.tabIndex)
    this.setData({serviceList})
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})